package com.zllkj.mm.api.network;

import com.zllkj.mm.api.network.exception.ApiErrorCode;
import com.zllkj.mm.api.network.exception.ApiException;
import com.zllkj.mm.util.KLog;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.adapter.rxjava.HttpException;

public abstract class BaseCallback<T> implements Callback<T> {

    protected abstract void onSucc(Response<T> response);

    protected abstract void onFail(String msg);

    protected void onFail(int code, String msg) {
    }

    protected void onComplete() {

    }


    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            if (response.code() != 0) {
                onSucc(response);
            } else {
                onFail(response.message());
            }
        } else {
            onFail(response.message());
        }
        onComplete();
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        if (t instanceof HttpException) {

        } else if (t instanceof IOException) {

        } else if (t instanceof ApiException) {
            ApiException exception = (ApiException) t;
            int code = exception.getErrorCode();
            switch (code) {
                case ApiErrorCode.ERROR_SESSION_INVALID:
                    KLog.e("sessionid过期");
                    break;

            }

            onFail(code, exception.getMessage());
        }

        onFail(t.getMessage());
        onComplete();
    }
}
